/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.tyf.common.web.controller.advice;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tyf.common.exception.CanIgnoredException;
import com.tyf.common.exception.MyselfMsgException;
import com.tyf.common.log.LogUtils;
import com.tyf.common.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

/**
 * 
 * @ClassName: DefaultExceptionHandler<br>
 * @Description: controller默认的异常处理<br>
 * @author liutao<br>
 * @date 2016年10月10日上午9:12:23<br>
 *
 */
@ControllerAdvice(annotations = {Controller.class})
public class DefaultExceptionHandler {

    /**
	 * 统一异常处理返回,只处理程序已确定的异常（CanIgnoredException,MyselfMsgException）<br>
	 * 未捕获的异常则走500页面的错误处理
	 * @param e 异常
	 * @param req http请求
	 * @return resultMap 封装的结果集map
	 */
	@ExceptionHandler({ CanIgnoredException.class, MyselfMsgException.class})
	@ResponseBody
	public Map<String, Object> processCertainException(Exception e, HttpServletRequest req, HttpServletResponse response) {
		Map<String, Object> resultMap = Maps.newHashMap();
		ResultVO flag = new ResultVO();
		flag.setRetCode(ResultVO.ERROR_CODE); // 异常默认code

		// 异常处理
		if (e instanceof CanIgnoredException) { // 可忽略的异常
			flag.setRetCode(ResultVO.WARN_CODE);
			flag.setRetMsg(e.getMessage());
		} else if (e instanceof MyselfMsgException) { // 自定义异常
			flag.setRetMsg(e.getMessage());
		}else{
			flag.setRetMsg(e.getMessage());
		}

		LogUtils.logInfo(e.getMessage(), e);
		// 返回结果
		resultMap.put("flag", flag);
		return resultMap;
	}
}
